package com.zust513.controller;

import com.zust513.entity.Region;
import com.zust513.entity.User;
import com.zust513.service.UserService;
import com.zust513.utils.ServletContextUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequiredArgsConstructor
@RequestMapping("user")
public class UserController {

    @Autowired
     private final UserService userService;

    @GetMapping("adminHome")
    public String adminHome(ModelMap model) {
        return "admin/home";
    }
    @GetMapping("courierHome")
    public String courierHome(ModelMap model) {
        return "courier/home";
    }

    //登录
    @GetMapping("login")
    public String Login() {
        return "login";
    }
    @PostMapping("login")
    public String DoLogin(@RequestParam("username") String username,
                          @RequestParam("passwordHash") String passwordHash, ModelMap model) {
        User LoginUser = userService.login(username, passwordHash);
        if (LoginUser == null) {
            model.addAttribute("msg", "用户名或密码错误");
            return "login";}
        if (LoginUser.getRole() == null) {
            model.addAttribute("msg", "用户角色错误");
            return "login";
        }
        ServletContextUtil.setCurUser(LoginUser);
        String Role = LoginUser.getRole();
        if (Role.equals("admin")) {
            return "redirect:/admin";
        } else if (Role.equals("courier")) {
            return "redirect:/courier/main";
        } else if (Role.equals("user")) {
            return "redirect:/clients/clientmain";
        }
        return "redirect:/user/login";
    }



    //注册
    @GetMapping("register")
    public String Register(ModelMap model) {
        List<Region> deliveryAreas = userService.getDeliveryAreas();
        model.addAttribute("deliveryAreas", deliveryAreas);
        return "register";
    }
    @PostMapping("register")
    public String DoRegister(User user, ModelMap model,Integer deliveryArea) {
        User RegisterUser = userService.register(user,deliveryArea);
        if (RegisterUser == null) {
            model.addAttribute("msg", "注册失败,用户名或邮箱或手机已存在");
            return "register";
        }
        return "redirect:/user/login";
    }

    //退出登录
    @GetMapping("logout")
    public String Logout() {
        return "login";}}

